import api from '../../../api/index';
import Toast from '@vant/weapp/toast/toast';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userid: null,
    authorUser: null,
    pageNum: 0,
		pageSize: 10,
		noMor: false,
		noData: false,
    articleList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var { userid } = options
    this.setData({
      userid
    })
    console.log(userid);
    this.getauthorUser(userid)
    this.article(userid)
  },
  // 删除文章
  onclickdelete(e) {
    let { id } = e.currentTarget.dataset
    try {
      api.get(`/api/hxhealth/forum/article/remove/${id}`).then((res) => {
        console.log(res);
        this.setData({
          articleList: []
        })
        this.getauthorUser(this.data.userid)
        this.article(this.data.userid)
      });
    } catch (e) {
      console.error(e);
    }
  },
  getauthorUser(id) {
    console.log(id);
    try {
      api.get(`/api/hxhealth/forum/author/info/${id}`).then((res) => {
        console.log(res);
        // res[0].images = JSON.parse(res[0].media).images
        // res[0].zanusers = res[0].zanusers?JSON.parse(res[0].zanusers):''
        this.setData({
          authorUser: res[0]
        })
        // this.commentList(res[0].id)
        // console.log(res[0]);
        // Toast.clear();
      });
    } catch (e) {
      console.error(e);
    }
  },
  loadImages (array) {
    array.forEach(item => {
      item.imgsList = []
      item.videosList = []
      if(item.media) {
        const mediaObj = JSON.parse(item.media)
        if(mediaObj.images) {
          mediaObj.images.forEach(img => {
            item.imgsList.push(img.file)
          })
        }
        if(mediaObj.videos) {
          mediaObj.videos.forEach(v => {
            item.videosList.push(v.file)
          })
        }
      }
    })
    return array
  },
  article(id) {
    const actions = {
      data: {
        userid: id
      },
      head: {
        firstresult: this.data.pageNum,
        maxresults: this.data.pageSize,
        bodytype: 'flat',
      }
    };
    try {
      api.post('/api/hxhealth/forum/article/author', actions).then((res) => {
        if (res.length == 0) { //请求的数据为空，没有数据
          if (this.data.pageNum == 0) { // 第一页都没有数据，直接显示暂无数据
            this.setData({
              noData: true,
            })
          } else { // 不为第一页时，请求的数据为空，说明没有更多数据了，把pageNum减一，是为了下次触底可以继续请求刷新，万一有了新数据也可以正常显示出来
            this.setData({
              noMor: true,
              pageNum: 0
            })
          }
        } else {  // 请求的结果有数据
					const dataList = this.loadImages([...this.data.articleList, ...res])
          if (res.length == this.data.pageSize) { // 请求的数据为10条，说明下一页可能还有数据，列表添加上新的数据，把其他状态设为不显示
            this.setData({
              articleList: dataList,
              noMor: false,
              noData: false
            })
          } else { // 请求的数据没有10条，说明下一页已经暂时没有数据了，列表添加上新的数据，底部显示暂无更多数据
            this.setData({
              articleList: dataList,
              noMor: true,
              noData: false
            })
          }
        }
      });
    } catch (e) {
      console.error(e);
    }
  },
  onDesicClick(e) {
    var id = e.currentTarget.dataset.id
    wx.navigateTo({ url: `/community/pages/desc/index?id=${id}` } );
  },
  onPalyClick(e) {
    var id = e.currentTarget.dataset.id
    wx.navigateTo({ url: `/community/pages/playvideo/index?id=${id}` });
  },
  // 预览图片
  previewImage(e) {
    console.log(e);
    let { sources, index } = e.currentTarget.dataset
    sources.filter(i => {
      console.log(i);
      i.type = i.type == 2 ? 'video' : 'image'
      i.url = i.file
    })
    console.log(
      sources
    );
    wx.previewMedia({
      sources,
      current: index
    })
  },

  // 视频加载完成，改变视频的宽高
  videometa(e) {
    var that = this;
    //获取系统信息
    wx.getSystemInfo({
      success(res) {
        //视频的高
        var height = e.detail.height;

        //视频的宽
        var width = e.detail.width;

        //算出视频的比例
        var proportion = height / width;

        //res.windowWidth为手机屏幕的宽。
        var windowWidth = res.windowWidth;

        //算出当前宽度下高度的数值
        height = proportion * windowWidth;
        that.setData({
          height,
          width: windowWidth
        });
      }
    })
  },

  // 图片加载后判断图片宽高比例
  oneImageLoad(e) {
    const { width, height } = e.detail
    height >= width && this.setData({ isHeightMode: true })
  },
  // 关注
  onFollowClick() {
    try {
      api.get(`/api/hxhealth/forum/author/follow/${this.data.userid}`).then((res) => {
        console.log(res);
        Toast.success('关注成功');
        this.getauthorUser(this.data.userid)
        this.article(this.data.userid)
      });
    } catch (e) {
      console.error(e);
    }
  },
  // 已关注
  onUnFollowClick() {
    try {
      api.get(`/api/hxhealth/forum/author/unfollow/${this.data.userid}`).then((res) => {
        console.log(res);
        Toast.success('取消成功');
        this.getauthorUser(this.data.userid)
        this.article(this.data.userid)
      });
    } catch (e) {
      console.error(e);
    }
  },
  // 文章点赞、取消
  onclickzans(e) {
    var item = e.currentTarget.dataset.item
    let index = e.currentTarget.dataset.index
    if(item.zaned == 'false') {
      try {
        api.get(`/api/hxhealth/forum/article/zan/${item.id}`).then((res) => {
          console.log(res);
          Toast.success('点赞成功');
          const list = this.data.articleList
          let num = Number(list[index].zans)
          list[index].zans = num + 1
          list[index].zaned = 'true'
          this.setData({
            articleList: list
          })
        });
      } catch (e) {
        console.error(e);
      }
    } else {
      try {
        api.get(`/api/hxhealth/forum/article/unzan/${item.id}`).then((res) => {
          console.log(res);
          Toast.success('取消成功');
          const list = this.data.articleList
          let num = Number(list[index].zans)
          list[index].zans = num - 1
          list[index].zaned = 'false'
          this.setData({
            articleList: list
          })
        });
      } catch (e) {
        console.error(e);
      }
    }
  },
  // 文章收藏、取消
  onclickcollects(e) {
    var item = e.currentTarget.dataset.item
    if(item.zaned == 'false') {
      try {
        api.get(`/api/hxhealth/forum/article/collect/${item.id}`).then((res) => {
          console.log(res);
          Toast.success('收藏成功');
          this.getauthorUser(this.data.userid)
          this.article(this.data.userid)
        });
      } catch (e) {
        console.error(e);
      }
    } else {
      try {
        api.get(`/api/hxhealth/forum/article/uncollect/${item.id}`).then((res) => {
          console.log(res);
          Toast.success('取消成功');
          this.getauthorUser(this.data.userid)
          this.article(this.data.userid)
        });
      } catch (e) {
        console.error(e);
      }
    }
  },
  // 查看文章详情
  godescPage(e) {
    console.log(e);
    var id = e.currentTarget.dataset.id
    wx.navigateTo({ url: `/community/pages/desc/index?id=${id}` });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if ((this.data.pageNum + 1) * this.data.pageSize == this.data.articleList.length) { 
      // 数据列表的数量刚好等于页数*每页条数，可以请求下一页
        this.setData({
          pageNum: this.data.pageNum + 1, // 一般上拉触底是为了加载更多分页数据，所以这里页数自增
        });
        // 查询列表方法
        this.article(this.data.userid)
        
      } else { 
      // 数据列表的数量不等于页数*每页条数，说明当前页数据不足10条，已经没有更多数据了
        this.setData({
          noMor: true  // 这里在页面最底部显示一排文字，没有更多数据了
        })
      }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})